<template>
  <div class="main" v-loading="pageLoading" element-loading-text="加载中">
    <div class="nav">
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            :to="{ path: '/data-converge/indicator-manage-special' }"
            ><span class="breadcrumb-title">列表</span></el-breadcrumb-item
          >
          <el-breadcrumb-item>编辑体系</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <div class="content">
      <div class="content-main">
        <!-- <span class="base-info-title">基本信息：</span> -->
        <div class="content-title">
          <svg-icon icon-class="标题图标" />
          <span>基本信息：</span>
        </div>
        <el-form
          ref="taskFormRef"
          :model="taskForm"
          :rules="taskFormRules"
          label-width="110px"
        >
          <div class="base-info">
            <el-row :gutter="60">
              <el-col :span="8">
                <el-form-item label="指标体系名称" prop="name">
                  <el-input
                    v-model="taskForm.name"
                    :disabled="isEdit"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="体检城市" prop="medicalCity">
                  <el-select
                    v-model="taskForm.medicalCity"
                    placeholder="请选择"
                    :disabled="isEdit"
                  >
                    <el-option
                      v-for="item in cityOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="体检年份" prop="medicalYear">
                  <el-select
                    v-model="taskForm.medicalYear"
                    placeholder="请选择"
                    filterable
                    :disabled="isEdit"
                  >
                    <el-option
                      v-for="item in yearOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="24">
                <el-form-item label="指标体系说明" prop="indicatorDesciption">
                  <el-input
                    v-model="taskForm.description"
                    type="textarea"
                    :rows="3"
                    resize="none"
                    :disabled="isEdit"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-divider></el-divider>
          <!-- <div class="divide-line"></div> -->
          <!-- <span class="indicator-tree-title">指标体系：</span> -->
          <div class="content-title">
            <svg-icon icon-class="标题图标" />
            <span>指标体系：</span>
          </div>
          <div class="operation">
            <div class="operation-left">
              <icon-button
                icon="加"
                title="新增维度"
                @click.native="addDimension"
                v-if="isRelease === '0'"
                :isclick="isEdit"
              ></icon-button>
              <!-- type="primary1" -->
              <!-- <icon-button icon="下载" title="一键导入" type="plain1" :isclick="isEdit"></icon-button>
              <el-button type="text" >模板下载</el-button> -->
            </div>
            <div class="operation-right" v-if="indicatorSystemName">
              <span>
                <i>*{{ indicatorSystemName }}</i
                >体检指标体系，包含<i>{{ dimensionTree.length }}个维度</i>，共计
                <i>{{ indicatorLength }}个指标 </i>
              </span>
            </div>
          </div>
          <el-divider></el-divider>
          <!-- <div class="divide-line"></div> -->
          <div class="indicator-list">
            <div class="indicator-list-left">
              <!-- <div class="indicator-list-left-divider"></div> -->
              <div class="indicator-list-left-bottom">
                <el-tree
                  :data="dimensionTree"
                  node-key="id"
                  ref="tree"
                  class="dimension-tree"
                  :highlight-current="true"
                  :default-expand-all="true"
                  :expand-on-click-node="false"
                  empty-text="请先添加维度"
                  @node-click="handleNodeClick"
                  height="80%"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <div class="custom-tree-node-title">
                      <img
                        v-if="data.hasOwnProperty('icon')"
                        :src="data.icon"
                      />
                      <!-- <svg-icon v-if="data.hasOwnProperty('icon')" :icon-class="data.label" class="title-icon" :class="currentData === data ? 'isActive': '' "/> -->
                      <svg-icon
                        v-else
                        icon-class="指标1"
                        class="index-icon"
                        :class="currentData === data ? 'isActive' : ''"
                      />
                      <!-- <img v-else src="../../assets/index.png" style="width: 15px;height: 15px;"/> -->
                      <!-- <span v-else style="width: 7px"></span> -->
                      <span>{{ node.label }}</span>
                    </div>
                    <span class="custom-tree-node-operation" v-if="!isEdit">
                      <template v-if="data.hasOwnProperty('children')">
                        <el-tooltip
                          effect="dark"
                          content="添加指标"
                          placement="top"
                        >
                          <svg-icon
                            icon-class="添加子目录"
                            @click.stop="addIndicator(data)"
                          ></svg-icon>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          content="编辑维度"
                          placement="top"
                        >
                          <svg-icon
                            icon-class="编辑"
                            @click.stop="editDimension(data)"
                          ></svg-icon>
                        </el-tooltip>
                      </template>
                      <el-tooltip effect="dark" content="删除" placement="top">
                        <svg-icon
                          icon-class="删除"
                          @click.stop="delNode(node, data)"
                        ></svg-icon>
                      </el-tooltip>
                    </span>
                  </span>
                </el-tree>
              </div>
            </div>
            <div class="indicator-list-divider"></div>
            <div
              class="indicator-list-right"
              v-loading="infoLoading"
              element-loading-text="加载中"
            >
              <template
                v-if="
                  indicatorForm.hasOwnProperty('id') &&
                  !indicatorForm.hasOwnProperty('children')
                "
              >
                <el-form
                  :model="indicatorForm"
                  label-width="125px"
                  label-position="top"
                >
                  <el-row :gutter="120">
                    <el-col :span="8">
                      <el-form-item label="指标释义">
                        <!-- <el-input
                          v-model="indicatorForm.indicatorParaphrase"
                          type="textarea"
                          :rows="3"
                          resize="none"
                        ></el-input> -->
                        <el-input
                          v-model="indicatorForm.indicatorParaphrase"
                          :disabled="isEdit"
                          :title="indicatorForm.indicatorParaphrase"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="指标类型">
                        <el-select
                          v-model="indicatorForm.indicatorType"
                          placeholder="请选择"
                          :disabled="isEdit"
                        >
                          <el-option
                            v-for="item in indicatorTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="评价标准">
                        <el-input
                          v-model="indicatorForm.evaluationCriterion"
                          :disabled="isEdit"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="120">
                    <el-col :span="8">
                      <el-form-item label="评价类型">
                        <el-select
                          v-model="indicatorForm.evaluationType"
                          placeholder="请选择"
                          :disabled="isEdit"
                        >
                          <el-option
                            v-for="item in evaluationTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="参考值">
                        <el-row v-if="indicatorForm.evaluationType === 2">
                          <el-col :span="11">
                            <el-input
                              v-model="indicatorForm.referenceValueOfRange[0]"
                              :disabled="isEdit"
                            ></el-input>
                          </el-col>
                          <el-col
                            :span="2"
                            style="display: flex; justify-content: center"
                          >
                            —
                          </el-col>
                          <el-col :span="11">
                            <el-input
                              v-model="indicatorForm.referenceValueOfRange[1]"
                              :disabled="isEdit"
                            ></el-input>
                          </el-col>
                        </el-row>
                        <el-input
                          v-model="indicatorForm.referenceValue"
                          v-else
                          :disabled="isEdit"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="指标单位">
                        <el-input
                          v-model="indicatorForm.indicatorUnit"
                          :disabled="isEdit"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="120">
                    <el-col :span="8">
                      <el-form-item label="关联指标体系名称">
                        <el-button
                          type="text"
                          @click="selectIndicator"
                          v-if="!isEdit"
                          >选择指标</el-button
                        >
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item
                    label="已关联指标"
                    v-if="
                      indicatorForm.selection &&
                      indicatorForm.selection.length > 0
                    "
                  >
                    <selection-table
                      :tableData="indicatorForm.selection"
                      @handleRemove="removeIndicator"
                      :isRelease="isRelease"
                      :isEdit="isEdit"
                    ></selection-table>
                  </el-form-item>
                </el-form>
              </template>
            </div>

            <el-card class="indicator-list-right" v-if="false"> </el-card>
          </div>
          <el-divider></el-divider>
          <!-- <div class="divide-line"></div> -->
          <el-form-item class="flex-center" v-if="isRelease === '0'">
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="isEdit = false" v-if="isEdit"
              >编辑</el-button
            >
            <el-button type="primary" @click="saveIndicatorSystem" v-else
              >保存</el-button
            >
            <!-- <el-button type="primary" @click="confirmAddIndicatorSystem">保存并发布</el-button> -->
            <el-button type="plain" @click="publish">发布</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 新增维度对话框 -->
    <el-dialog
      title="新增维度"
      :visible.sync="addDimensionDialogVisible"
      width="40%"
      @closed="handleAddDimensionDialogClosed"
    >
      <el-form
        ref="addDimensionFormRef"
        :model="addDimensionForm"
        label-width="120px"
        :rules="addDimensionFormRules"
      >
        <el-form-item label="维度名称" prop="dimensionName">
          <el-input
            type="text"
            v-model="addDimensionForm.dimensionName"
          ></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <div class="grid">
            <div
              class="icon-item"
              v-for="(item, index) of iconList"
              :key="index"
              @click="selectIcon(index, item)"
              ref="iconRef"
            >
              <img :src="item.content" />
              <span>{{ item.name }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="上传图标">
          <el-upload
            ref="uploadRef"
            :data="{ name: 'test' }"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList"
            :on-remove="handleRemove"
            accept=".png,.jpeg,.jpg"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过100kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDimensionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddDimension">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改维度名称对话框 -->
    <el-dialog
      title="修改维度名称"
      :visible.sync="editDimensionDialogVisible"
      width="30%"
    >
      <el-form
        ref="editDimensionFormRef"
        :model="editDimensionForm"
        label-width="120px"
      >
        <el-form-item label="维度名称" prop="dimensionName">
          <el-input
            type="text"
            v-model="editDimensionForm.dimensionName"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDimensionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditDimension"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 添加指标对话框 -->
    <el-dialog
      title="添加指标"
      :visible.sync="addIndicatorDialogVisible"
      width="30%"
      @closed="handleAddIndicatorDialogClosed"
    >
      <el-form
        ref="addIndicatorFormRef"
        :model="addIndicatorForm"
        label-width="120px"
        :rules="addIndicatorFormRules"
      >
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input
            type="text"
            v-model="addIndicatorForm.indicatorName"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addIndicatorDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddIndicator">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 确认保存/发布对话框 -->
    <el-dialog :visible.sync="confirmDialogVisible" width="30%" center>
      <div class="confirm-info">
        <i class="el-icon-warning-outline"></i>
        <span> 发布后不可修改，请确认是否发布？ </span>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmIndicatorSystemEdit(1)"
            >确认发布</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 选择关联的指标对话框 -->
    <el-dialog
      title="选择关联的指标"
      :visible.sync="selectRefIndicatorDialogVisible"
      width="60%"
      style="margin-top: -110px; overflow-y: hidden"
    >
      <!-- <el-cascader
        v-model="indicatorForm.relevanceIndicatorSystem"
        :options="indicatorSystemOptions"
        :props="{ multiple: true }"
        @change="handleChange"
        clearable
        popper-class="cus-popper"
      ></el-cascader> -->
      <indicator-table
        :tableData="indicatorTableData"
        :page.sync="page"
        :default-selection="indicatorForm.selection"
        @selection-change="handleSelectionChange"
      ></indicator-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selectRefIndicatorDialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="confirmSelectIndicator"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAreaList,
  getIconList,
  updateQuota,
  insertDimension,
  insertIndicator,
  // queryQuotaList,
  // getDimensionByQuotaId,
  // getIndicatorByDimensionId,
  uploadUrl,
  judgeQuoInfo,
  getQuotaByPkid,
  updateIndicator,
  updateIndicatorInfo,
  deleteIndicator,
  queryIndicator,
  deleteRelatIndicator,
  queryMulConditions,
} from '@api/indicator-manage'
import IconButton from '@c/icon-button'
import SvgIcon from '@c/svg-icon'
import IndicatorTable from './components/indicatorTable.vue'
import SelectionTable from './components/selectionTable.vue'

export default {
  components: {
    IconButton,
    SvgIcon,
    IndicatorTable,
    SelectionTable,
  },
  data() {
    return {
      id: '',
      uploadUrl,
      uploadHeaders: {
        'AUTH-TOKEN': JSON.parse(window.localStorage.getItem('user')).token,
      },
      fileList: [],
      iconList: [],
      activeStep: 0,
      taskForm: {
        name: '',
        medicalCity: '',
        medicalYear: '',
        description: '',
        dimensionTree: [],
      },
      taskFormRules: {
        name: [
          { required: true, message: '请填写指标体系名称', trigger: 'blur' },
        ],
        medicalCity: [
          { required: true, message: '请选择体检城市', trigger: 'change' },
        ],
        medicalYear: [
          { required: true, message: '请选择体检年份', trigger: 'change' },
        ],
        // description: [{ required: true, message: '请填写指标体系说明', trigger: 'blur' }],
      },
      taskFormRef: null,
      indicatorForm: {
        dutyDepartment: '',
        indicatorParaphrase: '',
        indicatorType: '',
        evaluationCriterion: '',
        evaluationType: '',
        referenceValue: '',
        indicatorUnit: '',
        relevanceIndicatorSystem: [],
        // hasRelevance: '1',
      },
      cityOptions: [],
      yearOptions: [...Array(new Date().getFullYear() + 1 - 2015)]
        .map((_, i) => {
          return {
            value: i + 2015,
            label: i + 2015 + '年',
          }
        })
        .reverse(),
      dutyDepartmentOptions: [],
      indicatorTypeOptions: [
        {
          value: 0,
          label: '基本指标',
        },
        {
          value: 1,
          label: '特色指标',
        },
        {
          value: 2,
          label: '补充指标',
        },
      ],
      evaluationTypeOptions: [
        {
          value: 0,
          label: '底线型',
        },
        {
          value: 1,
          label: '目标型',
        },
        {
          value: 2,
          label: '区间型',
        },
      ],
      indicatorSystemOptions: [],
      indicatorOptions: [],
      dimensionTree: [],
      editDimensionDialogVisible: false,
      editDimensionForm: {
        dimensionName: '',
        id: '',
      },
      addDimensionDialogVisible: false,
      addDimensionFormRef: null,
      addDimensionForm: {
        dimensionName: '',
        id: '',
        icon: '',
      },
      addDimensionFormRules: {
        dimensionName: [
          { required: true, message: '请填写维度名称', trigger: 'blur' },
        ],
        icon: [
          {
            required: true,
            message: '请选择图标',
            trigger: ['change', 'blur'],
          },
        ],
      },
      addIndicatorDialogVisible: false,
      addIndicatorFormRef: null,
      addIndicatorForm: {
        indicatorName: '',
        id: '',
      },
      addIndicatorFormRules: {
        indicatorName: [
          { required: true, message: '请填写指标名称', trigger: 'blur' },
        ],
      },
      currentDimension: {},
      iconRef: null,
      // 确认对话框
      confirmDialogVisible: false,
      delIndicatorList: [],
      // 选择关联的指标对话框
      selectRefIndicatorDialogVisible: false,
      indicatorTableData: [],
      selection: [],
      infoLoading: false, // 指标详情加载
      pageLoading: true,
      resArr: [],
      page: {
        name: '',
        dimensionId: '',
        year: '',
        areaId: '',
        quotaName: '',
        pageSize: 10,
        pageIndex: 1,
        total: 0,
      },
      currentData: '',
      currentSelection: [],
      isEdit: true,
      isRelease: '1',
      // pkid: this.$router.query.pkid
    }
  },
  computed: {
    indicatorSystemName() {
      return this.taskForm.medicalYear && this.taskForm.medicalCity
        ? this.taskForm.medicalYear +
            '年' +
            this.cityOptions.find(
              (item) => item.value === this.taskForm.medicalCity
            ).label
        : ''
    },
    indicatorLength() {
      let length = 0
      this.dimensionTree.forEach((item) => {
        length += item.children.length
      })
      return length
    },
    listenCityAndYear() {
      return this.taskForm.medicalCity && this.taskForm.medicalYear
        ? [this.taskForm.medicalCity, this.taskForm.medicalYear]
        : null
    },
  },
  methods: {
    transformTree(data) {
      return data.map((dimension) => {
        return {
          icon: dimension.icon,
          label: dimension.name,
          id: dimension.pkid,
          children: dimension.indexDataInfoList.map((indicator) => {
            return {
              ...indicator,
              label: indicator.name,
              id: indicator.pkid,
              indicatorParaphrase: indicator.introduction,
              indicatorType: indicator.indexType,
              evaluationCriterion: indicator.standard,
              evaluationType: indicator.standardType,
              indicatorUnit: indicator.indexUnit,
            }
          }),
        }
      })
    },
    addDimension() {
      this.addDimensionDialogVisible = true
    },
    confirmAddDimension() {
      this.$refs.addDimensionFormRef.validate((valid) => {
        if (valid) {
          if (
            this.dimensionTree.findIndex(
              (item) => item.label === this.addDimensionForm.dimensionName
            ) === -1
          ) {
            const params = {
              name: this.addDimensionForm.dimensionName,
              iconId: this.addDimensionForm.iconId,
              quotaId: this.$route.query.pkid,
            }
            insertDimension(params).then((res) => {
              if (res.success) {
                const id = res.data
                this.dimensionTree.push({
                  id: id,
                  label: this.addDimensionForm.dimensionName,
                  icon: this.addDimensionForm.icon,
                  children: [],
                })
                this.addDimensionDialogVisible = false
              }
            })
          } else {
            this.$message.warning('不能添加重复的维度')
          }
        }
      })
    },
    addIndicator(data) {
      this.currentDimension = data
      this.addIndicatorDialogVisible = true
      // console.log(data);
    },
    confirmAddIndicator() {
      this.$refs.addIndicatorFormRef.validate((valid) => {
        if (valid) {
          this.currentDimension.children.push({
            id:
              '' +
              this.currentDimension.id +
              (this.currentDimension.children.length + 1),
            label: this.addIndicatorForm.indicatorName,
            referenceValueOfRange: ['', ''],
            isAdded: true,
          })
          // 渲染视图
          this.dimensionTree = [...this.dimensionTree]
          this.addIndicatorDialogVisible = false
          //添加指标后保存
          this.saveIndicatorSystem('save')
        }
      })
    },
    saveIndicator(tag) {
      this.dimensionTree.forEach((item) => {
        item.children.forEach((indicator) => {
          // if (indicator?.evaluationType === 2) {
          //   indicator.referenceValueOfRange = indicator.referenceValue.split('-');
          // }
          const params = {
            id: indicator.id,
            dimensionId: item.id,
            // dataGroup:
            //   Object.prototype.hasOwnProperty.call(indicator, 'relevanceIndicatorSystem') &&
            //   indicator.relevanceIndicatorSystem.length > 0
            //     ? indicator.relevanceIndicatorSystem.map(item => item[item.length - 1])
            //     : [],
            dataGroup:
              Object.prototype.hasOwnProperty.call(indicator, 'selection') &&
              indicator.selection.length > 0
                ? indicator.selection.map((item) => item.pkid)
                : [],
            indexDataInfo: {
              name: indicator.label,
              introduction: indicator.indicatorParaphrase,
              indexType: indicator.indicatorType,
              standard: indicator.evaluationCriterion,
              standardType: indicator.evaluationType,
              // 参考值，区分区间型和其他类型
              // referenceValue: indicator.referenceValue,
              referenceValue:
                indicator?.evaluationType === 2 &&
                indicator.referenceValueOfRange
                  ? indicator.referenceValueOfRange.join('-')
                  : indicator.referenceValue,
              indexUnit: indicator.indicatorUnit,
            },

            serviceInfos: [],
          }
          if (indicator.isAdded && tag === 'save') {
            insertIndicator(params).then((res) => {
              if (res.success) {
                // console.log();
              }
            })
          } else {
            updateIndicator(params).then((res) => {
              if (res.success) {
                console.log('update', params)
              }
            })
          }
        })
      })
    },
    editDimension(data) {
      // console.log(data);
      this.editDimensionForm.dimensionName = data.label
      this.editDimensionForm.id = data.id
      this.editDimensionDialogVisible = true
    },
    selectIndicator() {
      this.selectRefIndicatorDialogVisible = true
      this.page.name = ''
      this.page.dimensionId = ''
      this.page.year = ''
      this.page.areaId = ''
      this.page.quotaName = ''
      this.page.pageSize = 10
      this.page.pageIndex = 1
      this.getData()
    },
    confirmEditDimension() {
      this.dimensionTree.forEach((item) => {
        if (item.id === this.editDimensionForm.id) {
          item.label = this.editDimensionForm.dimensionName
        }
      })
      this.editDimensionDialogVisible = false
    },
    handleAddDimensionDialogClosed() {
      this.$refs.addDimensionFormRef.resetFields()
      // 去除icon选中状态
      this.$refs.iconRef.forEach((item) => {
        item.className = 'icon-item'
      })
      // 清空文件
      this.fileList = []
      // 重置iconList
      this.initIconList()
    },
    handleAddIndicatorDialogClosed() {
      this.$refs.addIndicatorFormRef.resetFields()
    },
    handleNodeClick(data, node) {
      this.currentData = data
      // 判断指标还是维度节点
      if (data?.icon) {
        // 维度
        this.indicatorForm = data
        data = {}
      } else {
        // 新增的指标
        if (data?.isAdded) {
          this.indicatorForm = data
          this.indicatorForm.selection = []
          return
        }
        // 编辑已有的指标
        this.infoLoading = true
        // console.log('data.id', data.id);
        this.getDataInfo(data.id, node)
      }
    },
    getDataInfo(id, node) {
      queryIndicator(id).then((res) => {
        if (res.success) {
          const info = {
            ...res.data,
            indicatorParaphrase: res.data.introduction,
            groupId: res.data.groupId ? res.data.groupId : '',
            indicatorType: this.indicatorTypeOptions.find(
              (item) => item.value == res.data.indexType
            )?.value, // 指标类型
            evaluationType: this.evaluationTypeOptions.find(
              (item) => item.value == res.data.standardType
            )?.value, // 评价类型
            evaluationCriterion: res.data.standard,
            referenceValueOfRange:
              res.data.standardType == '2'
                ? res.data.referenceValue.split('-')
                : ['', ''],
            indicatorUnit: res.data.indexUnit,
            label: res.data.name,
            id: res.data.pkid,
            relevanceIndicatorName: res.data.relationIndexInfo
              ? res.data.relationIndexInfo.map((item) => item.name).join(',')
              : null,
            selection: res.data.relationIndexInfo ?? [],
          }

          // data = indicator;
          this.indicatorForm = info

          // console.log('info', info);
          if (node) {
            this.dimensionTree.forEach((dimension, index) => {
              if (dimension.id === node.parent.data.id) {
                dimension.children.forEach((indicator, i) => {
                  if (indicator.id === id) {
                    this.dimensionTree[index].children[i] = info
                  }
                })
              }
            })
          }
          // this.dimensionTree = [];
        }
        this.infoLoading = false
      })
    },
    selectIcon(index, data) {
      this.$refs.iconRef.forEach((item) => {
        item.className = 'icon-item'
      })
      if (index < 8) {
        this.addDimensionForm.dimensionName = data.name ?? ''
      }
      this.$refs.iconRef[index].className = 'icon-item bgc-gray'
      this.addDimensionForm.icon = data.content
      this.addDimensionForm.iconId = data.pkid
      this.$forceUpdate()
      this.$refs.addDimensionFormRef.validate()
    },
    async confirmIndicatorSystemEdit(publishState, tag) {
      await this.saveIndicator(tag)
      await this.delIndicatorByList(this.delIndicatorList)
      const params = {
        pkid: this.id,
        name: this.taskForm.name,
        areaId: this.taskForm.medicalCity,
        year: this.taskForm.medicalYear,
        describe: this.taskForm.description,
        dsIds: this.dimensionTree.map((item) => item.id),
        status: publishState,
      }
      updateQuota(params).then((res) => {
        if (res.success) {
          if (tag !== 'save') {
            this.isEdit = true
            this.$message.success(
              `${publishState === 1 ? '发布' : '保存'}成功！`
            )
            // this.$router.push('/indicator-manage/main');
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleChange() {
      // console.log(data, '----------');
    },
    handleSuccess(res, file) {
      // console.log(123123123313323);
      if (res.success) {
        this.addDimensionForm.iconId = res.data
        const icon = {
          content: URL.createObjectURL(file.raw),
          pkid: res.data,
          name: '',
        }
        this.iconList.push(icon)
      } else {
        this.$message.error(res.message + '，请重新上传。')
        this.fileList = []
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    handleRemove() {
      if (this.iconList.length > 8) {
        this.iconList.pop()
      }
    },
    initIconList() {
      getIconList(1).then((res) => {
        if (res.success) {
          this.iconList = res.data.map((item) => {
            return {
              ...item,
              icon: item.content
                ? URL.createObjectURL(
                    new Blob([item.content], {
                      type: 'text/xml',
                    })
                  )
                : null,
            }
          })
        }
      })
    },
    saveIndicatorSystem(tag) {
      this.$refs.taskFormRef.validate((valid) => {
        if (valid) {
          this.confirmIndicatorSystemEdit(0, tag)
        }
      })
    },
    publish() {
      // 表单验证
      this.$refs.taskFormRef.validate((valid) => {
        if (valid) {
          // 指标数量为0时不允许发布
          const indicatorTotal = this.dimensionTree.reduce(
            (total, item) => total + item.children.length,
            0
          )
          if (indicatorTotal > 0) {
            this.confirmDialogVisible = true
          } else {
            this.$notify({
              title: '提示',
              message: '需添加指标后才能发布！',
              duration: 2000,
            })
          }
        }
      })
    },
    delNode(node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex((d) => d.id === data.id)
      children.splice(index, 1)
      if (!data?.icon) {
        this.delIndicatorList.push(data.id)
      }

      this.saveIndicatorSystem('save')
      //当前选中的指标节点为被删除节点
      if (data.id === this.indicatorForm.id) {
        const catalog = this.dimensionTree.find(
          (item) => item.id === node.parent.data.id
        ).children
        const dataIndex = catalog.find((item) => item.id !== data.id)
        //当前删除的节点同目录下存在其他指标节点
        if (dataIndex) {
          this.indicatorForm = dataIndex
          setTimeout(() => {
            this.$refs.tree.setCurrentKey(dataIndex.id)
          }, 100)
        } else {
          this.whetherExistNode()
        }
      }

      //当前删除节点为维度节点
      if (!node.isLeaf) {
        this.whetherExistNode()
      }
    },
    //判断当前是否存在可选择的指标节点
    whetherExistNode() {
      const isExistChildren = this.dimensionTree.find(
        (item) => item.children.length
      )
      if (isExistChildren) {
        this.indicatorForm = isExistChildren.children[0]
        setTimeout(() => {
          this.$refs.tree.setCurrentKey(this.indicatorForm.id)
        }, 100)
      } else {
        this.indicatorForm = {
          dutyDepartment: '',
          indicatorParaphrase: '',
          indicatorType: '',
          evaluationCriterion: '',
          evaluationType: '',
          referenceValue: '',
          indicatorUnit: '',
          relevanceIndicatorSystem: [],
        }
      }
    },
    delIndicatorByList(list) {
      list.forEach((i) => {
        deleteIndicator(i)
      })
    },
    handleSelectionChange(selection) {
      // this.indicatorForm.selection = selection;
      this.currentSelection = selection
    },
    //获取第一个默认子节点
    getFirstChild(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (this.resArr[0]) {
          break
        }
        if (!arr[i].children) {
          this.resArr.push(arr[i])
          break
        } else {
          this.getFirstChild(arr[i].children)
        }
      }
      return this.resArr[0]
    },
    getData() {
      queryMulConditions(this.page).then((res) => {
        if (res.success) {
          this.indicatorTableData = res.data.list
          this.page.total = res.data.count
        }
      })
    },
    confirmSelectIndicator() {
      this.indicatorForm.selection = this.currentSelection
      this.saveIndicatorSystem('save')
      if (this.indicatorForm.groupId !== '') {
        this.updateRelatedIndicator()
      }
      console.log('this.icid==', this.indicatorForm)
      this.selectRefIndicatorDialogVisible = false
    },
    removeIndicator(item) {
      deleteRelatIndicator(item.row.pkid).then((res) => {
        if (res.success) {
          const currentNode = this.$refs.tree.getNode(this.currentData)
          // console.log('currentNode', currentNode);
          this.getDataInfo(this.currentData.id, currentNode)
          this.$message.success('取消关联成功')
        }
      })
    },
    updateRelatedIndicator() {
      const groupId = this.indicatorForm.groupId
      const dataId =
        this.indicatorForm.selection.length > 0
          ? this.indicatorForm.selection.map((item) => item.pkid)
          : []
      updateIndicatorInfo(groupId, dataId).then((res) => {
        if (res.success) {
          console.log('resssssssssssssss', res)
        }
      })
    },
    goBack() {
      this.$router.push('/indicator-manage/main')
    },
  },
  watch: {
    page() {
      this.getData()
      // if (!(newVal.pageIndex === oldVal.pageIndex && newVal.pageSize === oldVal.pageSize)) {
      // }
    },
    listenCityAndYear: function (newVal) {
      // console.log(1231212311);
      if (newVal) {
        const { year, areaId } = {
          year: this.taskForm.medicalYear,
          areaId: this.taskForm.medicalCity,
        }
        judgeQuoInfo(year, areaId).then((res) => {
          if (res.success) {
            // if (!res.data) {
            //   this.$message.error('该年份地区下已存在数据，请重新选择 体检城市 和 体检年份');
            //   this.taskForm.medicalCity = '';
            //   this.taskForm.medicalYear = '';
            // }
          }
        })
      }
    },
    'indicatorForm.relevanceIndicatorSystem': function (val, oldVal) {
      if (val?.length > 1) {
        if (val.length > oldVal.length) {
          let elementAdded
          val.forEach((item) => {
            oldVal.forEach((_) => {
              if (item[2] !== _[2] && item[0] === _[0]) {
                elementAdded = item
              }
            })
          })
          const copyVal = JSON.parse(JSON.stringify(val))
          // const elementAdded = val[val.length - 1];
          val.some((item, index) => {
            if (elementAdded[0] === item[0] && elementAdded[2] !== item[2]) {
              copyVal.splice(index, 1)
              return true
            }
          })
          this.indicatorForm.relevanceIndicatorSystem = copyVal
        }
      }
    },
    selectRefIndicatorDialogVisible(val) {
      if (val) {
        // this.page.name = '';
        // this.page.dimensionId = '';
        // this.page.year = '';
        // this.page.areaId = '';
        // this.page.quotaName = '';
        // this.page.pageSize = 10;
        // this.page.pageIndex = 1;
        // this.getData();

        //清空数据可执行表格数据变化的监听方法
        this.indicatorTableData = []
      }
    },
  },
  created() {
    this.id = this.$route.params.id
    this.isRelease = this.$route.query.remark
    // queryQuotaList({ pageIndex: 1, pageSize: 99999 }).then(res => {
    //   if (res.success) {
    //     this.indicatorSystemOptions = res.data.records.map(item => {
    //       return { label: item.name, value: item.pkid };
    //     });
    //     console.log('this.indicatorSystemOptions', this.indicatorSystemOptions);
    //     this.indicatorSystemOptions.forEach(item => {
    //       getQuotaByPkid(item.value).then(res1 => {
    //         if (res1.success && res1.data?.children) {
    //           item.children = res1.data.children.map(child1 => {
    //             return {
    //               label: child1.name,
    //               value: child1.pkid,
    //               children: child1.indexDataInfoList.map(child2 => {
    //                 this.indicatorTableData.push({
    //                   ...child2,
    //                   dimensionName: child1.name,
    //                   dimensionId: child1.pkid,
    //                   indicatorSystemName: item.label,
    //                   indicatorSystemId: item.value,
    //                 });
    //                 return {
    //                   ...child2,
    //                   label: child2.name,
    //                   value: child2.pkid,
    //                 };
    //               }),
    //             };
    //           });
    //         }
    //       });
    //     });
    //   }
    // });

    // queryMulConditions(this.page).then(res => {
    //   if (res.success) {
    //     this.indicatorTableData = res.data.list;
    //     this.page.total = res.data.count;
    //   }
    // });
    this.getData()
    getAreaList().then((res) => {
      if (res.success) {
        this.cityOptions = res.data.map((item) => {
          return {
            value: item.pkid,
            label: item.areaName,
          }
        })
      }
    })
    this.initIconList()
    getQuotaByPkid(this.id).then((res) => {
      if (res.success) {
        this.taskForm.name = res.data.name
        this.taskForm.medicalCity = this.cityOptions.find(
          (item) => item.label === res.data.area
        ).value
        this.taskForm.medicalYear = res.data.year
        this.taskForm.description = res.data.describe
        if (res.data.children) {
          this.dimensionTree = this.transformTree(res.data.children)
        }
        this.pageLoading = false
      }
      const dataTree = this.getFirstChild(this.dimensionTree)
      //默认高亮第一个可选中的节点
      setTimeout(() => {
        if (dataTree) {
          const dataNode = this.$refs.tree.getNode(dataTree)
          this.handleNodeClick(dataTree, dataNode)
          this.$refs.tree.setCurrentKey(dataTree.id)
        }
      }, 100)
    })
  },
}
</script>

<style lang="scss" scoped>
.indicator-list {
  height: 80%;
  width: 100%;
}
.dimension-tree {
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
    padding-right: 8px;
    line-height: 24px;
    .custom-tree-node-title {
      display: flex;
      align-items: center;
      line-height: 24px;

      img {
        width: 20px;
        fill: #c0c4cc;
        display: inline-block;
        margin-right: 5px;
      }
    }
    .custom-tree-node-operation {
      svg + svg {
        margin-left: 5px;
      }
    }

    .title-icon {
      width: 20px;
      height: 20px;
      margin-right: 5px;

      .isActive {
        color: #368fff;
      }
    }

    .index-icon {
      width: 16px;
      height: 16px;
      margin-right: 5px;

      .isActive {
        color: #368fff;
      }
    }
  }
}
i {
  font-style: normal;
  color: red;
}

.icon + .icon {
  margin-left: 20px;
}

.grid {
  position: relative;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  // grid-template-columns: repeat(4, minmax(0, 1fr));
  .icon-item {
    padding: 20px;
    height: 100px;
    text-align: center;
    width: 100px;
    float: left;
    font-size: 30px;
    color: #24292e;
    cursor: pointer;
    img {
      width: 100px;
      height: 80px;
      padding: 0 10px;
      box-sizing: border-box;
    }
  }

  span {
    display: block;
    width: 100px;
    height: 20px;
    font-size: 16px;
    line-height: 20px;
  }
}
.bgc-gray {
  // background-color: gray;
  border-color: #c5e3f1;
  background-color: #ecf6fb;
}

.nav {
  height: 40px;
  // background: #ffffff;
  // box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);
  border-radius: 2px;
  .breadcrumb {
    height: 40px;
    // padding-left: 25px;
    // padding-top: 15px;
    padding: 15px 0px 10px 25px;
    box-sizing: border-box;

    &-title {
      position: relative;
      margin-left: 11px;
      height: 21px;
      font-size: 15px;
      &::before {
        content: '';
        width: 5px;
        height: 16px;
        background: #10a6dd;
        border-radius: 3px;
        margin-right: 4px;
        display: inline-block;
        position: absolute;
        top: 50%;
        left: -11px;
        transform: translateY(-50%);
      }
    }
  }
  .divider {
    height: 1px;
    background: #e7f0ff;
    border-radius: 1px 1px 0px 0px;
  }
}

.content {
  width: calc(100% - 40px);
  height: calc(100% - 85px);
  position: absolute;
  top: 65px;
  bottom: 0;
  .divider {
    height: 1px;
    background: #e7f0ff;
    border-radius: 1px 1px 0px 0px;
  }
  .content-main {
    height: calc(100% - 50px);
    background: #ffffff;
    box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);
    border-radius: 2px;
    padding: 25px;
    // overflow: scroll;
    .base-info-title {
      position: relative;
      margin-left: 11px;
      height: 21px;
      font-size: 15px;
      bottom: 10px;
      &::before {
        content: '';
        width: 7px;
        height: 7px;
        background: #10a6dd;
        border-radius: 50%;
        margin-right: 4px;
        display: inline-block;
        position: absolute;
        top: 50%;
        left: -11px;
        transform: translateY(-50%);
      }
    }

    .el-form {
      height: calc(100% - 21px);

      .base-info {
        margin-top: 1rem;

        .el-row {
          width: 100%;
        }
        .el-form-item {
          .el-select {
            width: 100%;
          }
          .el-input {
            width: 100%;
          }
          .el-textarea {
            width: 100%;
          }
        }
      }
      .indicator-tree-title {
        position: relative;
        margin-left: 11px;
        font-size: 15px;
        &::before {
          content: '';
          width: 7px;
          height: 7px;
          background: #10a6dd;
          border-radius: 50%;
          margin-right: 4px;
          display: inline-block;
          position: absolute;
          top: 50%;
          left: -11px;
          transform: translateY(-50%);
        }
      }
      .form-footer {
        // text-align: left;
        margin-left: 0;
        margin-right: 23px;
        margin-top: 10px;
      }
      .indicator-list {
        height: 50%;
        width: 100%;
        display: flex;
        &-left {
          flex: 2;
          &-top {
            // height: 15%;
            width: 100%;
            display: flex;
            align-items: center;
            margin-top: 0.5rem;
            box-sizing: border-box;
            padding: 0 23px;
          }
          &-bottom {
            height: 100%;
            width: 100%;
            overflow: scroll;
            padding: 11px 5px;
            box-sizing: border-box;
          }
          &-divider {
            width: calc(100% - 1rem);
            height: 1px;
            background: #e7f0ff;
            border-radius: 1px 1px 0px 0px;
            margin: 0.5rem;
          }
        }
        &-right {
          flex: 7;
          box-sizing: border-box;
          padding: 11px 27px;
          overflow-x: hidden;
          overflow-y: scroll;
          .el-input {
            width: 100%;
          }
          .el-cascader {
            width: 100%;
          }
          .el-select {
            width: 100%;
          }
        }
        &-divider {
          width: 1px;
          height: 100%;
          background: #e7f0ff;
          border-radius: 0px 1px 1px 0px;
        }
      }
      .summarization {
        // text-align: center;
        position: relative;
        .all {
          text-align: center;
          margin-bottom: 81px;
        }
        .confirm-info {
          box-sizing: border-box;
          padding-top: 18px;
          padding-left: 51px;
        }
        ul {
          text-align: center;
          margin-top: 88px;
          padding: 0;
          li {
            text-align: left;
            position: relative;
            padding: 19px;
            margin: 0;
            list-style: none;
            display: inline-block;
            width: 20%;
            height: 88px;
            background-color: #f1f5fa;
            border-radius: 2px;
            .li-left {
              width: 100%;
              height: 100%;
              display: flex;
              flex-direction: column;
              .indicator-system {
                flex: 1;
                display: flex;
                align-items: center;
              }
              .system-name {
                flex: 1;
                margin-top: 16px;
              }
            }

            img {
              position: absolute;
              top: 50%;
              transform: translateY(-50%);
              right: 19px;
            }
          }
          li + li {
            margin-left: 38px;
          }
        }
      }
    }
  }
}
.flex-center {
  display: flex;
  justify-content: center;
  ::v-deep .el-form-item__content {
    margin: 0 !important;
  }
}
.el-divider--horizontal {
  margin: 10px 0;
}

.main {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  padding: 20px;
  background-color: #f4f8fe;
}
.el-button--primary1 {
  background-color: #02bcca;
  border-color: #02bcca;
  color: #fff;
  &:hover {
    background: #1fc4cf;
    border-color: #02bcca;
    color: #fff;
  }
}
.el-button--plain1 {
  color: #02bcca;
  border-color: #02bcca;
  &:hover {
    border-color: #02bcca;
  }
}
.el-button--plain {
  color: #10a6dd;
  border-color: #10a6dd;
  &:hover {
    border-color: #10a6dd;
  }
}
.operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}
.confirm-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  i {
    font-size: 100px;
  }
  span {
    font-size: 20px;
  }
}

::v-deep {
  .el-tree-node__content {
    height: 40px;
  }
  .el-textarea__inner {
    font-family: PingFang SC;
  }

  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    color: #368fff;
  }
}

.el-icon-warning-outline {
  margin: 0px 0px 20px 0px;
}
// .divide-line {
//   width: 1780px;
//   height: 1px;
//   color: #c0c4cc;
// }
.content-title {
  padding: 0px 0 2px 0;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #000000;
  > span {
    margin-left: 5px;
  }
}
</style>
